#include "camerastrategy.h"


CameraStrategy::CameraStrategy(int w, int h, int id)
    : ICaptureStrategy(w, h), itsCameraId(id)
{

}

int CameraStrategy::prepareVideoCapture()
{
    int ret = 0;
    do
    {
        if(!itsVideo.isOpened())
        {
            itsVideo.open(itsCameraId);                  //使用相机
            itsVideo.set(cv::CAP_PROP_FRAME_WIDTH, itsWidth);
            itsVideo.set(cv::CAP_PROP_FRAME_HEIGHT, itsHeight);

            auto numFrames = (int) itsVideo.get(cv::CAP_PROP_FRAME_COUNT);
            qDebug() << "numFrame: "<< numFrames;
            if(!itsVideo.isOpened())
            {
                QMessageBox mesg;
                mesg.warning(this,"Tip","摄像头无法打开!");
                break;
            }
        }

        constexpr int num = 3;
        cv::Mat images[num];
        for(int i = 0; i < num; i++)
        {
            itsVideo >> images[i];
            cv::cvtColor(images[i], images[i], cv::COLOR_RGB2GRAY);
            cv::waitKeyEx(30);
        }
        images[2] = imgMinusAvg(images[2]);
        itsBaseImage = images[2].clone();
        imshow("base", itsBaseImage);

    } while(false);

    return ret;
}

int CameraStrategy::getFrame(cv::Mat& frame)
{
    int ret = 0;

    do
    {
        if(!itsVideo.isOpened())
        {
            ret = -1;
            break;
        }

        itsVideo >> frame;
        if(frame.empty())
        {
            ret = -2;
            break;
        }
        else
        {
            ret = 0;
            break;
        }
    } while(false);

    return ret;
}
